package com.its.myalgorithm.day03;

import com.its.myalgorithm.day01.ArrayUtils;

import java.util.Arrays;

/**
 * @projectName: dgl-algorithm
 * @package: com.its.myalgorithm.day03
 * @className: BSExist
 * @author: DONG GL
 * @description: TODO 二分查找
 * @date: 2022/3/30 20:05
 * @version: 1.0
 */
public class BSExist {

    public static boolean find(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return false;
        }
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int index = (start + end) / 2;
            if (arr[index] == num) {
                //如果当前 等于 num 直接返回
                return true;
            } else if (arr[index] > num) {
                // 如果 arr[index] > num  则 舍去index右边位置 继续二分
                end = index - 1;
            } else {
                // 如果 arr[index] < num  则 舍去index左边位置 继续二分
                start = index + 1;
            }
        }
        return false;
    }

    public static boolean test(int[] arr, int num) {
        for (int i : arr) {
            if (i == num) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 10;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr = ArrayUtils.generateRandomArray(maxSize, maxValue);
            Arrays.sort(arr);
            int value = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
            if (test(arr, value) != find(arr, value)) {
                System.out.println("出错了！");
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");
    }

}
